import tkinter as tk
from tkinter import messagebox
import pyperclip
import random
import requests  # 新增，用于向fls.py后端发送数据

user_name = "BAOGUOMA"
password = "0000000069"

name_list = ["张嘉锡", "赵健磊", "郭泰瑞", "秦晓川", "卢旺程", "李翔", "顾鼎"]
stable_name_list = ["张嘉锡", "赵健磊", "郭泰瑞", "秦晓川", "卢旺程", "李翔", "顾鼎"]
score_list = [100, 100, 100, 100, 100, 100]
score_list_tosend = []

scorelbs = []
button05 = []
button10 = []
buttonsub05 = []
buttonsub10 = []
buttonrefine = []
buttonsubrefine = []
lbcheck = []


fls_url = "http://127.0.0.1:5000"  # 新增，假设fls.py运行在本地5000端口，根据实际情况修改

def score_additionn():
    global score_list
    addition = 0

    for score in score_list:
        addition += score

    addition = addition / 10
    return addition

def add05(index):
    global score_list
    global scorelbs

    score_list[index] += 5
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    check_points()

def sub05(index):
    global score_list
    global scorelbs

    score_list[index] -= 5
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    check_points()

def add10(index):
    global score_list
    global scorelbs

    score_list[index] += 10
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    check_points()

def sub10(index):
    global score_list
    global scorelbs

    score_list[index] -= 10
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    check_points()

def refine(index):
    global score_list
    global scorelbs

    score_list[index] += 5
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    for i in range(6):
        if (i!= index):
            score_list[i] -= 1
            scorelbs[i].config(text="当前分数为:" + str(score_list[i] / 10))
    check_points()

def subrefine(index):
    global score_list
    global scorelbs

    score_list[index] -= 5
    scorelbs[index].config(text="当前分数为:" + str(score_list[index] / 10))
    for i in range(6):
        if (i!= index):
            score_list[i] += 1
            scorelbs[i].config(text="当前分数为:" + str(score_list[i] / 10))
    check_points()


def check_points():
    addition = score_additionn()
    unused_points = addition - 60

    if (unused_points < -0.1):
        lbcheck[0].config(text=f"您还有{abs(unused_points)}点分数没有使用")
        return False
    elif (unused_points == 0):
        lbcheck[0].config(text=f"分数匹配平衡，确认后可提交")
        return True
    elif (unused_points > +0.1):
        lbcheck[0].config(text=f"您目前超额使用了{abs(unused_points)}点分数")
        return False

def check_additiion():
    addition = score_additionn()
    if (addition!= 60):
        return False
    elif (addition == 60):
        return True

def check_username(string):
    if string not in name_list:
        messagebox.showinfo(title='非班级内人员提示', message='您好，您不是这个课程种的同学，马老师提醒你要讲武德')
        return False
    elif string in name_list:
        messagebox.showinfo(title='BAOGUO_MA', message='欢迎评分，武林要一喝为贵的啊，谢谢朋友们!')
        return True

def print_username(EN):
    global user_name
    user_name = EN.get()
    print(user_name)
    return user_name

def print_password(EN):
    global password
    password = EN.get()
    print(password)
    return password

def login():
    global name_list
    global win

    if (check_username(user_name)):
        name_list = refresh_namelist(name_list, user_name)
        print(name_list)
        grading_mode()
        win.destroy()

def refresh_namelist(name_list, name):
    new_name_list = []
    for names in name_list:
        if (names!= name):
            new_name_list.append(names)

    random.shuffle(new_name_list)
    return new_name_list

def refresh_scorelist():
    global name_list
    global stable_name_list
    global score_list
    global score_list_tosend

    score_list_tosend1=[]

    for name in stable_name_list:
        for n in range(0,len(name_list)):
            if name_list[n] == name:
                score_list_tosend1.append(score_list[n])

    score_list_tosend = score_list_tosend1

def refresh_scorelisttosend():
    global user_name
    global score_list_tosend

    refresh_scorelist()
    newlist = []

    user_name_index = stable_name_list.index(user_name)
    checker = 0

    for index in range(0, 7):
        if checker == 0:
            if index == user_name_index:
                newlist.append("\\")
                checker = 1
            else:
                newlist.append(str(score_list_tosend[index]/10))

        elif checker == 1:
            newlist.append(str(score_list_tosend[index - 1]/10))

    score_list_tosend = newlist


def construct_text():
    global user_name, password, name_list, score_list

    refresh_scorelisttosend()

    if (check_points()):

        print(score_list_tosend)

        # 构建要发送的数据，格式为字典，包含用户名和对应分数列表
        data_to_send = {
            "username": user_name,
            "scores": [score for score in score_list_tosend]
        }

        try:
            # 发送POST请求到fls.py后端
            response = requests.post(f"{fls_url}/update_scores", json=data_to_send)
            if response.status_code == 200:
                messagebox.showinfo(title='提交成功', message='分数已成功提交并更新到网页端')
                pyperclip.copy(f"{user_name}同学，学号{password}给出的评分结果是:\n" + "\n".join(
                    [f"{name}:{score}" for name, score in zip(name_list, [score / 10 for score in score_list])]))
            else:
                messagebox.showinfo(title='提交失败', message='分数提交失败，请稍后再试')
        except requests.RequestException as e:
            messagebox.showinfo(title='网络错误', message=f'提交分数时出现网络错误: {e}')

    else:
        messagebox.showinfo(title='BAOGUO_MA', message='您给出的分数总和并未符合总和等于60的要求，\n符合要求后才能拷贝到剪贴板哦！')

def reset_scorelist():
    global score_list
    global scorelbs

    for i in range(6):
        score_list[i] = 100
        scorelbs[i].config(text="当前分数为:" + str(score_list[i] / 10))

    return 1

def grading_mode():
    global user_name
    global password

    win2 = tk.Toplevel()
    win2.title("BAOGUO_MA")

    str_title = str(user_name) + "同学，" + str(password) + "学号: 你的评分是:"
    print(user_name)
    print(password)
    print(str_title)

    label = tk.Label(win2, text=str_title, fg="blue", font=("微软雅黑", 10, "bold"))
    label.grid(row=0, columnspan=5, sticky="w", padx="10px", pady="10px")

    lb1 = tk.Label(win2, text=str(name_list[0]), font=("Arial", 10, "bold"))
    lb1.grid(row=1, sticky="w", pady=8, columnspan=5)
    lb2 = tk.Label(win2, text=str(name_list[1]), font=("Arial", 10, "bold"))
    lb2.grid(row=3, sticky="w", pady=8, columnspan=5)
    lb3 = tk.Label(win2, text=str(name_list[2]), font=("Arial", 10, "bold"))
    lb3.grid(row=5, sticky="w", pady=8, columnspan=5)
    lb4 = tk.Label(win2, text=str(name_list[3]), font=("Arial", 10, "bold"))
    lb4.grid(row=7, sticky="w", pady=8, columnspan=5)
    lb5 = tk.Label(win2, text=str(name_list[4]), font=("Arial", 10, "bold"))
    lb5.grid(row=9, sticky="w", pady=8, columnspan=5)
    lb5 = tk.Label(win2, text=str(name_list[5]), font=("Arial", 10, "bold"))
    lb5.grid(row=11, sticky="w", pady=8, columnspan=5)

    checklabel = tk.Label(win2, text="BAOGUO_MA提醒您现在可以开始匹配分数", font=("Arial", 10, "bold"))
    checklabel.grid(row=13, sticky="w", pady=8, columnspan=8)
    lbcheck.append(checklabel)

    bucopy = tk.Button(win2, text="确认并拷贝到剪贴板", command=construct_text)
    bucopy.grid(row=15, sticky="w", pady=8)

    burest = tk.Button(win2, text="回调至初始值", command=reset_scorelist)
    burest.grid(row=15, column=3, pady=8)

    bu_quit = tk.Button(win2, text="退出", width=10, command=win2.quit)
    bu_quit.grid(row=16, column=5, columnspan=2, sticky="e", pady=5)

    for row in range(6):
        scorelb = tk.Label(win2, text="当前分数为：" + str(score_list[row] / 10))
        scorelb.grid(row=(2 * (row + 1)), sticky="w", columnspan=5)
        scorelbs.append(scorelb)

        bu05 = tk.Button(win2, text="+0.5", command=lambda index=row: add05(index))
        bu05.grid(row=(2 * (row + 1) - 1), column=5)
        button05.append(bu05)

        busub05 = tk.Button(win2, text="-0.5", command=lambda index=row: sub05(index))
        busub05.grid(row=(2 * (row + 1)), column=5)
        buttonsub05.append(busub05)

        bu10 = tk.Button(win2, text="+1", command=lambda index=row: add10(index))
        bu10.grid(row=(2 * (row + 1) - 1), column=6)
        button10.append(bu10)

        busub10 = tk.Button(win2, text="-1", command=lambda index=row: sub10(index))
        busub10.grid(row=(2 * (row + 1)), column=6)
        buttonsub10.append(busub10)

        burefine = tk.Button(win2, text="↑0.5", command=lambda index=row: refine(index))
        burefine.grid(row=(2 * (row + 1) - 1), column=7)
        buttonrefine.append(burefine)

        busubrefine = tk.Button(win2, text="↓0.5", command=lambda index=row: subrefine(index))
        busubrefine.grid(row=(2 * (row + 1)), column=7)
        buttonsubrefine.append(busubrefine)

    win2.mainloop()

def sign_in_window():
    global user_name
    global password
    global win

    win = tk.Tk()
    win.title("BAOGUO_MA")

    win.resizable(False, False)

    lb1 = tk.Label(win, text="给分人姓名")
    lb1.grid(row=0, sticky="w")
    lb2 = tk.Label(win, text="给分人学号")
    lb2.grid(row=2, sticky="w")

    en1 = tk.Entry(win)
    en1.grid(row=1)

    en2 = tk.Entry(win)
    en2.grid(row=3)

    lb3 = tk.Label(win, text="BAOGUO_MA", fg="blue", font=("微软雅黑", 10, "bold"))
    lb3.grid(row=0, column=1, rowspan=4, padx="5px", pady="5px")

    bu_sign = tk.Button(win, text="登录", width=10, command=login)
    bu_sign.grid(row=4, column=0, columnspan=2, sticky="w", padx=20, pady=5)

    bu_quit = tk.Button(win, text="退出", width=10, command=win.quit)
    bu_quit.grid(row=4, column=1, columnspan=2, sticky="e", padx=10, pady=5)

    en1.bind("<KeyRelease>", lambda event: print_username(en1))
    en2.bind("<KeyRelease>", lambda event: print_password(en2))

    win.mainloop()

    return win

if __name__ == '__main__':
    sign_in_window()